<?php


chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir(dirname(__FILE__));

include_once $path."/../lib/core.class.php";


class Checkout extends IPlugin 
{

    function Checkout($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
    }
    
    function getPluginTag() { return "checkout"; }
    function getPluginName() { return "Checkout plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Checkout"; } break;
            case "MenuTitle" : { return "Checkout"; } break;
        };
        return $result;
    }
    


    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }
        

                $core = &getCoreInstance();
                $db = &$core->getProperty("db");

        $_cart = &$_SESSION["cart"];


        if(!count($_cart) || ("complete"==$_GET["page"] && ("YES"!=$_SESSION["cart_checkout"] || 0 >= $_GET["orderid"])))
        {
            header("location: ".$core->config['http_root']);
            exit();
        }

        switch ($_POST["event"]) {
            case "doSubmitCheckoutForm": {
//              debug($_POST);
                global $_P;
                $sql = "select shipment_price from shipment where shipment_id='".str2db($_POST['shipment'])."'";
                $scost = $db->getone($sql);
                $clients = new ccontrl();

                        if (isset($_P['client_ccexpdate_m']) and isset($_P['client_ccexpdate_y'])){
                        if(!is_numeric($_P['client_ccexpdate_m']) or $_P['client_ccexpdate_m'] > 12)
                        $_P['client_ccexpdate_m'] = 01;
                         
                        if(!is_numeric($_P['client_ccexpdate_y']))
                        $_P['client_ccexpdate_y'] = 05;
                
                        $_P['client_ccexpdate'] = $_P['client_ccexpdate_m'].$_P['client_ccexpdate_y'];
                        }
                        else{
                        $_P['client_ccexpdate'] = 0105;
                        }

                        $_P['ccexpdate'] = $_P['client_ccexpdate'];
                        $mmm = $_P['client_ccexpdate_m'];
                        $yyy = $_P['client_ccexpdate_y'];
                        unset($_P['client_ccexpdate_m'],$_P['client_ccexpdate_y'],$_P['client_ccexpdate']);
                        
                        /* REGISTERING CLIENT START IF CHECKED */
                        /*
                        if ($_P['reg_me'] == 'true'){
                                 $regme = 'true';
                                
                                $NewClient = array();
                                $NewClient['client_name'] = $_P['cc_fname'].$_P['cc_lname'];
                                $NewClient['client_email'] = $_P['cl']['login'];
                                $NewClient['client_password'] = $_P['cl']['password'];
                                $NewClient['client_phone'] = $_P['cc_phone'];
                                $NewClient['client_billing_name'] = $_P['cc_fname'].' '.$_P['cc_lname'];
                                $NewClient['client_billing_country']  = $_P['cc_country]'];
                                $NewClient['client_billing_adress1'] = $_P['cc_address'];
                                $NewClient['client_billing_adress2'] = $_P['cc_address2'];
                                $NewClient['client_billing_city'] = $_P['cc_city'];
                                $NewClient['client_billing_state'] = $_P['cc_state'];
                                $NewClient['client_billing_zip'] = $_P['cc_zip'];
                                $NewClient['client_billing_phone'] = $_P['cc_phone'];
                                $NewClient['client_shipping_name'] = $_P['sfname'].' '.$_P['slname'];
                                $NewClient['client_shipping_adress1'] = $_P['saddress1'];
                                $NewClient['client_shipping_adress2'] = $_P['saddress2'];
                                $NewClient['client_shipping_city'] = $_P['scity'];
                                $NewClient['client_shipping_state'] = $_P['sstate'];
                                $NewClient['client_shipping_zip'] = $_P['szip'];
                                $NewClient['client_shipping_country'] = $_P['scountry'];
                                $NewClient['client_cctype'] = $_P['cctype'];
                                $NewClient['client_ccnumber'] = $_P['ccnumber'];
                                $NewClient['client_cccvv'] = $_P['cccvv'];
                                $NewClient['client_ccholdername'] = $_P['ccholdername'];
                                $NewClient['client_ccexpdate_m'] = $mmm;
                                $NewClient['client_ccexpdate_y'] = $yyy;
                                
                                unset($_P['cl']);
                        
                                $nc = $clients->insertcd(Arraystr2db($NewClient), &$db); // >0 , works
                                $clients->setSessionCc($nc);
                        }
                        else{
                        $regme = 'false';
                        }
                        */
                        /* REGISTERING CLIENT END */

                $resp = '';
       
                       $db->Exec("insert into orders(data,ccexpdate,cctype, ccnumber, ccholdername, cccvv, pubdate, fname, lname, company, address1, address2, city, state, zip, country, email, phone,
                                        findus, findother,
                                        sfname, slname, saddress1, saddress2, scity, sstate, szip, scountry,
                                        price, status, shipment,discount)
                                values( ?, ?, ?, ?, ?, ?, now(),
                                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                                        ?, ?,
                                        ?, ?, ?, ?, ?, ?, ?, ?,
                                        ?, ?, ?, ?)", 0, array(
                        array(str2db(serialize($resp)),$_P['ccexpdate'], $_P['cctype'], $_P['ccnumber'], $_P['ccholdername'], $_P['cccvv'], $_P["cc_fname"], $_P["cc_lname"], '', $_P["cc_address"], $_P["cc_address2"], $_P["cc_city"],
                                        $_P["cc_state"], $_P["cc_zip"], $_P["cc_country"], $_P["cc_email"], $_P["cc_phone"],
                            '', '',
                            $_P["sfname"], $_P["slname"], $_P["saddress1"], $_P["saddress2"], $_P["scity"], $_P["sstate"],
                            $_P["szip"], $_P["scountry"],
                            $_SESSION['secure']['price']+$scost, 1, $_P['shipment'], $_SESSION['secure']['total_discount']

                        )
                ));
                
              $id = $db->getInsertID();


                #$cl_ = $clients->getSessionCc();
                /*
                if($cl_ < 0 or $cl_ == 0 or !isset($cl_) or $cl_ == ''){
                        $clients->setSessionCc($clients->getnonameclientid($db)); 
                } // if not client, and don`t want to be client, assigning noname client to order  
                
                
                $sql = "insert into clients_orders (cl_id,order_id) values('".$clients->getSessionCc()."','".$id."')"; //inserting into client_orders
                $db->Exec($sql);


                if ($regme == 'true'  and $cl_ > 0){
                        $clients->setSessionCc($cl_);

                }

                if ($regme == 'false' and $clients->getSessionCc() == $clients->getnonameclientid($db)){
                        $clients->setSessionCc(0);
                }
                */
                foreach ($_cart as $catalogid => $v)
                {
                                        if('single item' == $v['type']) {

                                    $db->Exec("insert into purchaseitems(order_id, catalogid, price, qty, title, image, warranty, purchaseitems_discount,package_slave) " .
                                            "values({$id}, {$catalogid}, ?, {$v[qty]}, ?, ?, {$v[warranty]}, {$v[item_discount]},0)", 0, array(array($v["price"], $v["title"], $v["thumbnail"])));
                // --------<START> | Added by Gendich | "qty log on store & mail alert" ---------------------------------                    
                                    $db->Exec("insert into store_history (catalog_id,date,action,qty) values ($catalogid,now(),'sell',-$v[qty])");
                                    
                                    $qty=$db->getone("select sum(qty) from store_history where catalog_id=$catalogid");
                                    $min_qty=$db->getone("select s_value from settings where s_key='min_qty'");
                                    $was_alert=$db->getone("select min_qty_alert from catalog where catalog_id=$catalogid");
                                    if ($qty<=$min_qty && !$was_alert)
                                    {
                                        $admin_mail=$db->getone("select s_value from settings where s_key='Administrator email'");
                                        $site = $core->config["system"]["www_name"];
                                        $now = date("Y-m-d H:i:s");   
                                            $msg = "
                                                <html>
                                                <body>
                                                    <b> Automatic system of the notification of the <font color=\"blue\">$site</font> informing you:</b> <br />
                                                    <b> </b>  <br />
                                                    Now: $now <br />
                                                    On this time minimum quantity of the goods in a warehouse (STORE) is achieved.<br /> 
                                                        Accept the appropriate measures, please ! <br /><br />
                                                            Minimum qnt = $min_qty; <br />
                                                            The rest = $qty. <br />
                                                    $message_status[$id_status] <br /> <br />
                                                <body>
                                                </html>";
                                            $mail = $core->getSnippet("email");
                                            $m_from=$core->config["system"]["mail_info"];
                                            $m_to=$admin_mail;
                                            $params = array(
                                                "to" => $m_to,
                                                "from" => $m_from,
                                                "body" => $msg,
                                                "subject" => "$site info",
                                                "html" => "1",  // 1/0                              
                                                            );
                                        $mm=$mail->doAction($params);
                                        $db->exec("update catalog set min_qty_alert=1 where catalog_id=$catalogid");
                                    }
                // --------<END> | Added by Gendich | ---------------------------------
                
                } //end if single item 
          elseif ('package' == $v['type']){
$catalogid = str2db($v['package_master']);
$slave_catalog_id = str2db($v['package_slave']);

    $db->Exec("insert into purchaseitems(order_id, catalogid, price, qty, title, image, warranty, purchaseitems_discount,package_slave) " .
              "values({$id}, $catalogid , ?, {$v[qty]}, ?, ?, {$v[warranty]}, {$v[item_discount]}, $slave_catalog_id)", 0, array(array($v["price"], str2db($v["title"]), $v["thumbnail"])));
                // --------<START> | Added by Gendich | "qty log on store & mail alert" ---------------------------------                    

                                    $db->Exec("insert into store_history (catalog_id,date,action,qty) values ({$v[package_master]}, now(), 'sell',-$v[qty])");
                                    $db->Exec("insert into store_history (catalog_id,date,action,qty) values ({$v[package_slave]}, now(), 'sell',-$v[qty])");
                                    
                                    $qty=$db->getone("select sum(qty) from store_history where catalog_id=$catalogid");
                                    $min_qty=$db->getone("select s_value from settings where s_key='min_qty'");
                                    $was_alert=$db->getone("select min_qty_alert from catalog where catalog_id=$catalogid");
                                    if ($qty<=$min_qty && !$was_alert)
                                    {
                                        $admin_mail=$db->getone("select s_value from settings where s_key='Administrator email'");
                                        $site = $core->config["system"]["www_name"];
                                        $now = date("Y-m-d H:i:s");   
                                            $msg = "
                                                <html>
                                                <body>
                                                    <b> Automatic system of the notification of the <font color=\"blue\">$site</font> informing you:</b> <br />
                                                    <b> </b>  <br />
                                                    Now: $now <br />
                                                    On this time minimum quantity of the goods in a warehouse (STORE) is achieved.<br /> 
                                                        Accept the appropriate measures, please ! <br /><br />
                                                            Minimum qnt = $min_qty; <br />
                                                            The rest = $qty. <br />
                                                    $message_status[$id_status] <br /> <br />
                                                <body>
                                                </html>";
                                            $mail = $core->getSnippet("email");
                                            $m_from=$core->config["system"]["mail_info"];
                                            $m_to=$admin_mail;
                                            $params = array(
                                                "to" => $m_to,
                                                "from" => $m_from,
                                                "body" => $msg,
                                                "subject" => "$site info",
                                                "html" => "1",  // 1/0                              
                                                            );
                                        $mm=$mail->doAction($params);
                                        $db->exec("update catalog set min_qty_alert=1 where catalog_id=$catalogid");
                                        
                                    }
                // --------<END> | Added by Gendich | ---------------------------------
              
              
              
          } // end elseif package  
                
        } //foreach in cart ends
                $_SESSION["cart_checkout"] = "YES";
                $_SESSION["xid"] = "{$id}";
                        
                header("location: /index.php?path=cart,checkout&page=mycomplete&orderid={$id}");             

                exit();

            } break;

            default:
            break;
        }

        return true;

    }


    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }

        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;
        
        $page = $_GET["page"];
        
        switch ($page)
        {
            case "mycomplete": {
                $page = $this->GetFinishView($core, $render, $db);

            } break;

            default:
                $page = $this->GetCheckoutView($core, $render, $db);
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }


    // ----------------------------------------------------------------------------------
    // --- [ Render Finish page ] ---------------------------------------------------------
    // ----------------------------------------------------------------------------------
    
    
    
    
        function GetFinishView(&$core, &$render, &$db)
        {
            $info_conf = $core->config['system'];
            
                $xid = $_SESSION["xid"];
                        if(!isset($xid) or $xid = '' or !is_numeric($xid)){
                                $xid = str2db($_GET['orderid']);
                        }

                $z = $db->getAll("select * from orders where id={$xid}");
        
        if(count($z)<=0)
        {
            header("location: /index.php");
            exit();
        }
        $z = $z[0];
        $to = $z["email"];
        $name = $z["fname"].' '.$z["lname"];
        
        $_cart = $_SESSION["cart"];
        //debug($_cart);
        $rows = "<table cellpadding=2 cellspacing=2 border=0>
            <tr>
                <td colspan=4 align=left >Your cart:</td>
            </tr>
            <tr>
                <th align=\"left\"><b>Item</b></th>
                <th align=\"left\"><b>Price</b></th>
                <th align=\"left\"><b>Qty</b></th>
                <!--<th align=\"left\"><b>Extended Warranty</b></th>-->
                <!--<th align=\"left\"><b>Discount</b></th>-->
                <th align=\"left\"><b>Sub-total</b></th>
            </tr>
        ";
        $price = 0;
        $ship_price = db2str($db->getone("select shipment_price from shipment where shipment_id = '".str2db($z['shipment'])."'"));
        $ship_name  = db2str($db->getone("select shipment_title from shipment where shipment_id = '".str2db($z['shipment'])."'"));

        foreach ($_cart as $k => $v){
                $_cart[$k]['warranty'] = $db->getone("select warrantytype_price from products_warranty_types where warrantytype_id = ".$v['warranty']);
        }
                $result="";
                //debug($_cart);
        foreach ($_cart as $k => $v)
        {
                        $result[]=array("pid" => $k, "cid" => $db->getone("select parent_id from catalog where catalog_id=$k"),"title" => $v[title], "desc" => $db->getone("select short_desc from catalog where catalog_id=$k"));
            $rows .= ($rows=="" ? "" : "<br />\n").
                    "<tr>
                        <td>{$v[title]}</td>
                        <td>\${$v[price]}</td>
                        <td>{$v[qty]}</td>
                        <!--<td>{$v[warranty]}</td>-->
                        <!--<td>{$v[item_discount]}</td>-->
                        <td>\$".($v["qty"]*$v["price"]+$v['warranty']-$v['item_discount'])."</td>
                    </tr>
                    ";
            $price += $v["qty"]*$v["price"]+$v['warranty']-$v['item_discount'];
        }
        #\$".$ship_price."
        $rows .= "\n<tr>
                <td colspan=2>&nbsp;</td>
                <td colspan=2 align=center>Shipping: $ship_name </td>
            </tr>";
        $rows .= "\n<tr>
                <td colspan=2>&nbsp;</td>
                <td colspan=2 align=center>Total price: \${$z['price']}</td>
            </tr>\n<table>\n\n";
        
        $message = "<html><body>\n<h1>Congratulation!</h1>\n
        <br />
        <br />
        <center> Hello $name </center><br />
        Thank you for your order<br />
        Thanks for shopping at {$info_conf[logo_name]} This email is confirmation that we have received your order.<br />
        You will receive another email when the order has shipped.<br />
        <p>Your order number is <b>$xid</b>.</p> 
              
        If you will have any questions or comments for us please send an email to <a href=\"mailto:{$info_conf[cust_service]}\">{$info_conf[cust_service]}</a> 
        or call our toll free customer service number at {$info_conf[customer_service_number]}.<br />
        Representatives are available 7 days aweek, 9am- 5:00pm EST.<br />
        
        Thank you for shopping at {$info_conf[logo_name]} <br />
        
        {$info_conf[logo_name]}'s Customer Service<br />
        {$info_conf[customer_service_number]}<br />
        <a href=\"mailto:{$info_conf[cust_service]}\">{$info_conf[cust_service]}</a><br />
        <a href=\"{$info_conf[www_name]}\">{$info_conf[www_name]}</a><br />
        <hr>
        <br />
        Order N $xid <br />
        Items shipped to : <br />
       
        <b>First Name</b>: {$z[fname]}<br>
        <b>Last Name</b>: {$z[lname]}<br>
        <b>Address1</b>: {$z[address1]}<br>
        <b>Address2</b>: {$z[address2]}<br>
        <b>City</b>: {$z[city]}<br>
        <b>State</b>: {$z[state]}<br>
        <b>Zip</b>: {$z[zip]}<br>
        <b>Country</b>: {$z[country]}<br>
        <b>Phone</b>: {$z[phone]}<br>
        <b>Email</b>: {$z[email]}<br>
        <br />
        <br />
        <b>Shipping information:</b><br />
        <b>First Name</b>: {$z[sfname]}<br>
        <b>Last Name</b>: {$z[slname]}<br>
        <b>Address1</b>: {$z[saddress1]}<br>
        <b>Address2</b>: {$z[saddress2]}<br>
        <b>City</b>: {$z[scity]}<br>
        <b>State</b>: {$z[sstate]}<br>
        <b>Zip</b>: {$z[szip]}<br>
        <b>Country</b>: {$z[scountry]}<br>
        
        Cart details:<br />
        {$rows}
        <br />
        <hr>
                
        <br />
        Thanks!<br />
        <br />
        Sincerely yours,<br />
        {$info_conf[prj_title]}<br />
        <br /><br />
        <br />
        </body>
        </html>\n\n\n
        ";
        
        /* To send HTML mail, you can set the Content-type header. */ 
        $headers  = "MIME-Version: 1.0\r\n"; 
        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
    
        /* additional headers */ 
        $headers .= "From: {$info_conf[prj_title]} store <{$info_conf[sales_mail]}>\r\n"; 
    
        $headers .= "Cc: {$info_conf[sales_mail]}\r\n"; 
        //$headers .= "Bcc: {$info_conf[sales_mail]}\r\n"; 
        $today = date("D , j-M , G:i:s T Y");
        #@mail($z["email"], "Order #".$_GET['orderid']."# ".$today." | {$info_conf[logo_name]}", $message, $headers);
        #@mail("{$info_conf[mail_info]}", "Order #{$_GET[orderid]} {$info_conf[logo_name]}", $message, $headers);
        $render->assign("test", $message);
        unset($_SESSION["secure"],$_SESSION["cart"], $_SESSION["cart_checkout"], $_SESSION['xcount'], $_SESSION['xprice'], $_SESSION['xid']);
        
                $render->assign("result", $result);
                
        $render->assign("mail_info", $info_conf['mail_info']);
        $render->assign("logo_name", $info_conf['logo_name']);

        return "congratulation.tpl.php";
    }
    
    
    
    
    // ----------------------------------------------------------------------------------
    // --- [ Render cart page ] ---------------------------------------------------------
    // ----------------------------------------------------------------------------------
    
    function GetCheckoutView(&$core, &$render, &$db)
    {
        $pid = 0;
        if(isset($_GET["pid"]) && $_GET["pid"]>=0)
        {
            $pid = $_GET["pid"];
        }

        foreach($_SESSION['cart'] as $key => $v){
                if($v['qty'] < 0){$_SESSION['cart'][$key]['qty'] = 1;}
        }

        
        $_cart = $_SESSION["cart"];

        $all_warranty = 0;

        foreach($_cart as $k => $v)
        {
                if (file_exists($core->config["file_root"]."/inventory/".$v[thumbnail]) && is_file($core->config["file_root"]."/inventory/".$v[thumbnail])) 
                {
                        list($w_size,$h_size)=explode(',',$this->getimgsizes($core->config["file_root"],$v[thumbnail]));
                        $default_w_size=70;
                        $default_h_size=77;
                        $size="";
                        if ($w_size>$h_size && $w_size>$default_w_size)
                                $size=" width=\"{$default_w_size}\" ";
                        if ($h_size>$w_size && $h_size>$default_h_size)
                        $size=" height=\"{$default_h_size}\" ";
                        
                        $_cart[$k][thumbnail] = "<img alt='' $size src=\"/inventory/".$_cart[$k][thumbnail]."\" border=\"0\" >";
                } else 
                {
                        $_cart[$k][thumbnail] = "<img alt='' src='/img/no_image.jpg' border=0 height=70/>";
                }
                //$value_warranty = $db->getOne("select warrantytype_price from products_warranty_types where warrantytype_id = '".$_cart[$k]['warranty']."'");
                $_cart[$k]['price'] = number_format($_cart[$k]['price'],2,'.',',');     
                $_cart[$k]['warranty'] = number_format($value_warranty * $_cart[$k]['qty'],2,'.',',');       
                $f = str_replace(",", "", $_cart[$k]['price']); 
                $q = $_cart[$k]['qty'];
                
                $_cart[$k]['item_discount'] = number_format($_cart[$k]['item_discount'] * $q, 2,'.',',');
                $_cart[$k]['subtotal'] = number_format($f * $q - $_cart[$k]['item_discount'] + $_cart[$k]['warranty'],2,'.',',');;
                //debug($_cart[$k]['subtotal']);
                //$_cart[$k]['subtotal'] = number_format($_cart[$k]['subtotal'],2,'.',',');             
                
                $_cart[$k]['title'] = stripslashes($_cart[$k]['title']);
                $_cart[$k][qty_on_stock]=$db->getone("select sum(qty) from store_history where catalog_id=$k");
                $all_warranty += $_cart[$k]['warranty'];
                
                $_cart[$k][cid] = $db->getone("select parent_id from catalog where catalog_id=$k");
        $_cart[$k][id] = $k;        
        }
        
        $render->assign("cart", $_cart);

        $price = 0;
        
        if (isset($_SESSION['secure']['price']) and $_SESSION['secure']['price'] > 0) {
        $price = $_SESSION['secure']['price'];
        }
        else {
        foreach($_cart as $v)
        {
            $price += $v["qty"] * $v["price"];
        }
        $price += $all_warranty;
             }
        $price_nformat = number_format($price,2,'.',',');
        $render->assign("price", $price_nformat);
             
        if (isset($_SESSION['secure']['total_discount']) and $_SESSION['secure']['total_discount'] > 0)
        $render->assign("total_discount", $_SESSION['secure']['total_discount']);

        $acount = $this->getallcd($this->getSessionCc(), $db);

        if($acount != '' and is_array($acount) and isne($acount)){

                $render->assign("already_client", 'true');
        
                $render->assign("acount", $acount);
                $render->assign("exp_m",          substr($acount['client_ccexpdate'],0,2));
                $render->assign("exp_y",          substr($acount['client_ccexpdate'],2,2));


/*                                              */
/*              VALID YEARS AND MONTHS ASSIGN   */
/*                    START                     */

                        $today = getdate();
                        $today_year = $today['year'];
                        $today_mon  = $today['mon'];
                        
                        for($i=0;$i<6;$i++){
                                $goodyears[]['year'] = substr($today_year + $i,2,4);
                                
                                
                        }                       
                                
                                
                                for($i=1;$i<13;$i++){
                                        
                                        
                                                $goodmonths[]['months'] = $i;
                                        
                                }
                                
                                
                                
                                $i = 1;
                                foreach($goodmonths as $k => $v){
                                        if(strlen($v['months']) == 1){
                                                $m[$i] = '0'.$v['months'];      
                                        }
                                        else{
                                                $m[$i] = $v['months']; 
                                        }
                                        $i++;
                                }
                                
                                for($i=0;$i<$today_mon;$i++){
                                        #unset($m[$i]);
                                }
                                                                
                                
                                //debug($m);
                                //debug($goodyears);
                                $render->assign("years",          $goodyears);       
                        $render->assign("months",         $m);       

/*                                              */
/*              VALID YEARS AND MONTHS ASSIGN   */
/*                    END                       */


                                                                 }
        else{
                $render->assign("already_client", 'false');

/*                                              */
/*              VALID YEARS AND MONTHS ASSIGN   */
/*                    START                     */

                        $today = getdate();
                        $today_year = $today['year'];
                        $today_mon  = $today['mon'];
                        
                        for($i=0;$i<6;$i++){
                                $goodyears[]['year'] = substr($today_year + $i,2,4);
                                
                                
                        }                       
                                
                                
                                for($i=1;$i<13;$i++){
                                        
                                        
                                                $goodmonths[]['months'] = $i;
                                        
                                }
                                
                                
                                
                                $i = 1;
                                foreach($goodmonths as $k => $v){
                                        if(strlen($v['months']) == 1){
                                                $m[$i] = '0'.$v['months'];      
                                        }
                                        else{
                                                $m[$i] = $v['months']; 
                                        }
                                        $i++;
                                }
                                
                                for($i=0;$i<$today_mon;$i++){
                                        #unset($m[$i]);
                                }
                                                                
                                
                                //debug($m);
                                //debug($goodyears);
                                $render->assign("years",          $goodyears);       
                        $render->assign("months",         $m);       

/*                                              */
/*              VALID YEARS AND MONTHS ASSIGN   */
/*                    END                       */


        }
                
                $sql = "select * from shipment where active='Y' and shipment_price >= '0' and shipment_title != '' order by shipment_price";
                $shipment_methods = ArrayDb2Str($db->getall($sql));
        $render->assign("shipment", $shipment_methods);
                if ($this->getSessionCc()>0) $balance=$db->getone("select balance from clients where client_id=".$this->getSessionCc());
                else $balance=0;
                $render->assign("balance", $balance); 
                        
        return "checkoutform.tpl.php";
    }



        function getallcd($client_id,&$db)                      { /* returns array(db from string) */
                $sql = "select * from clients where client_id='".str2db($client_id)."'";
                $r = $db->getrow($sql);
                $r = Arraydb2str($r);
                return $r;                      
        }

        function getSessionCc()                                 {
                $x = $_SESSION['cc']['client_id'];
                return($x);
                        
        }
        
// ----------------------------------------------------------------------------------
// --- [ GET IMAGES SIZE ] ----------------------------------------------------------
// ----------------------------------------------------------------------------------

        function getimgsizes($froot,$img){ 
                if(isne($img) && is_file($froot.'/inventory/'.$img)) {
                        $img = $froot.'/inventory/'.$img;
                        $ar = getimagesize($img);
                        $arrr = $ar[0].','.($ar[1]+50);
                        return $arrr;
                }
                return "";
        } 


};


?>
